import os

from django.contrib import auth
from django.http import HttpResponse
from django.shortcuts import redirect
from django.shortcuts import render

from bank_help import models
from tools import data_tools


# 主页
def home(r):
    return render(r, 'base.html')


# 简单日平台追踪项目
# @cache_page(30)
def simple_day_show(r):
    return render(r, 'simple_day.html', data_tools.simple_daily())


# 日平台详细
# @cache_page(30)
def detail_day_show(r):
    return render(r, 'detail_day.html', data_tools.detail_daily())


# @cache_page(30)
def quarter_show(r):
    return render(r, 'quarter.html', data_tools.month_data())


def compete_show(r):
    return render(r, 'compete.html', data_tools.compete_show())


def phases_compete_show(r):
    return render(r, 'phases_compete.html', data_tools.phases_compete_show())


# 登入页面
def login(r):
    # post请求处理
    error_msg = ''
    if r.method == "POST":
        username = r.POST.get('userName', None)
        password = r.POST.get('password', None)
        userInfo = models.UserInfo.objects.filter(username=username, password=password).first()
        if userInfo:
            r.session["user"] = userInfo
            return redirect('/index.html')
        else:
            error_msg = '用户密码错误'

    return render(r, 'login.html', {'error_msg': error_msg})


def logout(r):  # 注销
    auth.logout(r)
    return redirect("/login/")


# 队伍分析模块
def staff_analyst(r):
    # 如果post方法，则对数据进行分析
    if r.method == 'POST':
        try:
            file = r.FILES.get('file')
            file_path = os.path.join('upload', '人员清单.xlsx')
            # 使用chunks
            up_file = open(file_path, mode='wb')
            for i in file.chunks():
                up_file.write(i)
            up_file.close()
            # 获得绝对路径
            # file_abspath = os.path.abspath(file_path)
            rs = data_tools.add_staff_analyst(file_path)
            return HttpResponse(rs)
        except Exception as e:
            return HttpResponse(e)

    return render(r, 'staff_analyst.html', data_tools.show_staff_analyst())


# 调转到404
def page_not_found(request, exception):
    return render(request, '404.html')
